<template>
	<view class="container">
		<!-- 搜索栏 -->
		<search-box />
		<!-- 轮播图 -->
		<swiper :interval="2000" class="carousel" indicator-dots="true" indicator-active-color="#D0EBEA" circular
			@change="swiperChange">
			<swiper-item v-for="(item, index) in carouselList" :key="index" class="carousel-item"
				@click="navSwiper(item)">
				<image :src="item.url" />
			</swiper-item>
		</swiper>
		<!-- 广告区域 -->
		<view class="ad-1" v-if="ads.length>0">
			<image @click="navAD(ads[0])" :src="ads[0].url" mode="scaleToFit"></image>
		</view>
		<!-- 资源标签区域 -->
		<scroll-view scroll-x="true" scroll-with-animation scscroll-left="120" class="tag-section">
			<view v-for="(tag,index) in tagList" :key="index" v-if="index*2<tagList.length" class="tag-group">
				<!-- 分类上下两行显示 -->
				<view @click="navToTag(tagList[index*2].tagName)" class="tag-item">
					<view>
						<text>{{tagList[index*2].tagName}}</text>
					</view>
				</view>
				<view @click="navToTag(tagList[index*2+1].tagName)" class="tag-item" v-if="index*2+1<tagList.length">
					<view>
						<text>{{tagList[index*2+1].tagName}}</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<view id="nav-bar" class="nav-bar">
			<view v-for="(item,index) in tabBars" :key="item.value" class="nav-item"
				:class="{current: index === tabCurrentIndex}" :id="'tab'+index" @click="changeTab(index)">
				{{item.name}}
			</view>
		</view>

		<swiper id="swiper" :style="{height: swiperHeight+'px'}" :duration="300" :current="tabCurrentIndex"
			@change="changeTab">
			<!-- 推荐资源 -->
			<swiper-item>
				<view class="swiper-item-0">
					<!-- <scroll-view scroll-y="true" style="height:100%" @scrolltolower="loadMoreRecommend"> -->
					<resource-list :resourceList="recommendResourceList" :cols="1"></resource-list>
					<uni-load-more :status="recommendLoadingType"></uni-load-more>
					<!-- </scroll-view> -->
				</view>
			</swiper-item>
			<!-- 视频号直播间 -->
			<swiper-item>
				<view class="swiper-item-1">
					<!-- #ifdef MP-WEIXIN -->
					<!-- 视频号直播 -->
					<view class="" v-for="(liveWechatFinderUserName,index) in liveWechatFinderUserNameArray" v-if="applicationConfig.liveWechatPublicEnabled">
						<wx-live :finderUserName="liveWechatFinderUserName.trim()"></wx-live>
					</view>
					
					<!-- 小程序直播 -->
					<view class="room-list" v-if="applicationConfig.liveWechatPrivateEnabled">
						<view v-for="(item, index) in roomList" :key="index" class="room-item" @click="navToRoom(item)"
							v-if="roomList.length>0">
							<view class="image-wrapper">
								<image :src="item.cover_img" mode="aspectFill"></image>
							</view>
							<text class="title clamp">{{item.name}}</text>
							<view class="desc-box">
								<text>{{item.anchor_name}}</text>
							</view>
						</view>
					</view>
					<uni-load-more :status="roomLoadingType" v-if="applicationConfig.liveWechatPrivateEnabled"></uni-load-more>
					<!-- #endif -->
				</view>
			</swiper-item>
			<!-- 专栏 -->
			<swiper-item>
				<view class="swiper-item-2">
					<!-- <scroll-view scroll-y="true" style="height:100%" @scrolltolower="loadMoreGroup"> -->
					<resource-group :group="group" v-for="group in groupList"
						v-if="group.resourceList.length>0"></resource-group>
					<uni-load-more :status="groupLoadingType"></uni-load-more>
					<!-- </scroll-view> -->
				</view>
			</swiper-item>
		</swiper>
		<login-banner></login-banner>
		<!-- 新人领取优惠券和积分 -->
		<u-mask :show="showGift" :mask-click-able="false">
			<view class="gift">
				<view class="gift-title">
					新人有礼
				</view>
				<view class="gift-desc">
					恭喜您获得以下福利!
				</view>
				<view class="gift-image">
					<image src="../../static/image/gift.png"></image>
				</view>

				<view class="gift-content">
					<view class="gift-item" v-if="giftPoint.welfareType == 'POINT'">
						<view class="gift-item-label">
							积分
						</view>
						<view class="gift-item-value">
							<button><text class="tip">{{giftPoint.pointGiven}}</text></button>
						</view>
					</view>

					<view class="gift-item" v-for="giftCoupon in giftCouponList">
						<!-- 优惠券 -->
						<view class="gift-item-label">
							优惠券{{giftCoupon.couponDTO.limitPerUser}}张
						</view>
						<view class="gift-item-value">
							<button>{{giftCoupon.couponDTO.name}}</button>
						</view>
					</view>

				</view>
				<view class="gift-message">
					{{receiveGiftMessage}}
				</view>
				<view class="gift-action">
					<u-button :loading="receiveLoading" :ripple="true" @click="receiveProfitWelfare">立即领取</u-button>
				</view>
			</view>
			<view class="gift-close">
				<u-icon size="80" name="close-circle" @click="showGift=false"></u-icon>
			</view>
		</u-mask>
	</view>
</template>

<script>
	import resourceGroup from '@/components/resource-group.vue'
	import searchBox from '@/components/search-box.vue'
	import loginBanner from '@/components/login-banner.vue'
	import resourceList from '@/components/resource-list.vue'
	// #ifdef MP-WEIXIN
	import wxLive from '@/wxcomponents/wx-live/index'
	// #endif
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		components: {
			resourceGroup,
			searchBox,
			loginBanner,
			resourceList,
			// #ifdef MP-WEIXIN
			wxLive
			// #endif
		},
		data() {
			return {
				liveWechatFinderUserNameArray: [], //视频号id
				groupLoadingType: '', //专栏加载状态
				recommendLoadingType: '', //推荐加载状态
				roomLoadingType: '', //直播间加载状态
				recommendPageNo: 1, //推荐查询默认页码
				roomPageNo: 1, //直播间默认页码
				groupPageNo: 1, //专栏查询默认页码
				pageSize: 10, //分页查询每页数据条数
				swiperCurrent: 0, //轮播图index
				carouselList: [], //轮播图数据
				tabBars: [{
					name: '推荐'
				}, {
					name: '直播'
				}, {
					name: '专栏'
				}],
				tabCurrentIndex: 0,
				ads: [], //广告
				groupList: [], //资源组
				swiperHeight: 0,
				roomList: [], //直播间
				tagList: [], //标签列表
				recommendResourceList: [], //推荐资源列表
				showGift: false, //新人积分赠送和优惠券领取弹窗
				giftList: [], //新人专享数据列表
				giftResourceList: [], //新人专享商品
				giftCouponList: [], //新人可领取优惠券
				giftPoint: {}, //新人可领取积分
				receiveLoading: false,
				receiveGiftMessage: ''
			};
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint', 'applicationConfig'])
		},
		onLoad() {
			//关联的多个视频号ID
			this.liveWechatFinderUserNameArray = this.applicationConfig.liveWechatFinderUserName.split(',');
			this.inquirySwiper();
			this.inquiryAd();
			this.searchResourceGroup();
			this.searchRecommendResource(() => {
				//设置swiper的高度
				this.$nextTick(() => {
					this.setSwiperHeight();
				});
			});
			this.inquiryResourceTag();
			this.searchLiveRooms();
			this.inquiryProfitWelfare();
		},
		onShow() {
			//登录后如果没有领取优惠券和积分, 每次首页都会弹窗提示领取
			if (this.hasLogin && !this.userInfo.profitWelfareReceived) {
				if (this.giftPoint.welfareType == 'POINT' || this.giftCouponList.length > 0) {
					this.receiveGiftMessage = '';
					this.showGift = true; //有待领取新人福利, 打开领取弹窗
				}
			}
		},
		//加载更多
		onReachBottom() {
			if (this.tabCurrentIndex == 0)
				this.loadMoreRecommend();
			else if (this.tabCurrentIndex == 1){
				//小程序直播才加载更多房间, 视频一次加载全部
				if(this.applicationConfig.liveWechatPrivateEnabled)
					this.loadMoreRoom();
			}
			else if (this.tabCurrentIndex == 2)
				this.loadMoreGroup();
		},
		methods: {
			//轮播图切换
			swiperChange(e) {
				this.swiperCurrent = e.detail.current;
			},
			//轮播图
			inquirySwiper() {
				this.$api.request.slider({}, res => {
					if (res.body.status.statusCode === '0') {
						this.carouselList = res.body.data.swipers;
						this.swiperLength = this.carouselList.length;
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//轮播图链接
			navSwiper(item) {
				this.$api.util.navSwiper(item);
			},
			//首页广告
			inquiryAd() {
				this.$api.request.advert({
					location: '首页'
				}, res => {
					if (res.body.status.statusCode === '0') {
						this.ads = res.body.data.ads;
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//广告链接
			navAD(item) {
				this.$api.util.navAD(item);
			},
			navToTag(tagName) {
				uni.navigateTo({
					url: '/pages/resource/search-result?tagName=' + tagName
				})
			},
			changeTab(e) {
				if (typeof e === 'number') {
					this.tabCurrentIndex = e;
				} else if (typeof e === 'object') {
					this.tabCurrentIndex = e.detail.current
				}
				this.$nextTick(() => {
					this.setSwiperHeight();
				});
			},
			/* 动态设置siper的高度, swiper组件是固定高度, 如果在swiper-item里面使用scroll-view, 又会造成页面有两个滚动盒,造成用户体验不好 */
			setSwiperHeight() {
				let that = this;
				let element = '.swiper-item-' + this.tabCurrentIndex;
				let query = uni.createSelectorQuery().in(that);
				query.selectAll(element).boundingClientRect();
				query.exec((res) => {
					if (res && res[0] && res[0][0]) {
						that.swiperHeight = res[0][0].height;
					}
				});
			},
			//分页查询资源组
			searchResourceGroup(callback) {
				let searchData = {
					'keyArray': ['IS_ENABLED', 'IS_DISPLAYED_HOME'],
					'enabled': true,
					'displayedHome': true,
					'startIndex': (this.groupPageNo - 1) * this.pageSize,
					'pageSize': this.pageSize,
				};
				this.groupLoadingType = 'loading';
				this.$api.request.searchResourceGroup(searchData, res => {
					uni.stopPullDownRefresh();
					if (res.body.status.statusCode === '0') {
						var groupList = res.body.data.groups;
						if (this.groupPageNo === 1)
							this.groupList = groupList;
						else
							this.groupList = this.groupList.concat(groupList);
						var total = res.body.data.total;
						if (this.groupList.length >= total) {
							this.groupLoadingType = 'noMore';
						} else {
							this.groupLoadingType = 'more';
						}
					} else {
						this.groupLoadingType = 'more';
						console.log(res.body.status.errorDesc);
					}
					if (callback) callback();
				}, true);
			},
			searchRecommendResource(callback) {
				let that = this;
				let searchData = {
					keyArray: ['IS_RECOMMEND'],
					recommend: true,
					startIndex: (this.recommendPageNo - 1) * this.pageSize,
					pageSize: this.pageSize
				}
				this.recommendLoadingType = 'loading';
				that.$api.request.searchResource(searchData, res => {
					if (res.body.status.statusCode === '0') {
						var esourceList = res.body.data.resourceList;
						this.recommendResourceList = this.recommendResourceList.concat(esourceList);
						var total = res.body.data.total;
						if (this.recommendResourceList.length >= total) {
							this.recommendLoadingType = 'noMore';
						} else {
							this.recommendLoadingType = 'more';
						}
					} else {
						this.recommendLoadingType = 'more';
						console.log(res.body.status.errorDesc);
					}
					if (callback) callback();
				}, true);
			},
			//上滑加载更多推荐资源
			loadMoreRecommend() {
				if (this.recommendLoadingType == 'noMore') {
					return;
				}
				this.recommendPageNo = this.recommendPageNo + 1;
				this.searchRecommendResource(() => {
					this.$nextTick(() => {
						this.setSwiperHeight();
					});
				});
			},
			//上滑加载更多专栏
			loadMoreGroup() {
				if (this.groupLoadingType == 'noMore') {
					return;
				}
				this.groupPageNo = this.groupPageNo + 1;
				this.searchResourceGroup(() => {
					this.$nextTick(() => {
						this.setSwiperHeight();
					});
				});
			},
			//上滑加载更多直播间
			loadMoreRoom() {
				if (this.roomLoadingType == 'noMore') {
					return;
				}
				this.roomPageNo = this.roomPageNo + 1;
				this.searchLiveRooms(() => {
					this.$nextTick(() => {
						this.setSwiperHeight();
					});
				});
			},
			// 直播间
			searchLiveRooms(callback) {
				let searchData = {
					'startIndex': (this.roomPageNo - 1) * this.pageSize,
					'pageSize': this.pageSize
				};
				//加载中
				this.roomLoadingType = 'loading';
				this.$api.request.wechatLiveRoomList(searchData, res => {
					uni.stopPullDownRefresh();
					if (res.body.status.statusCode === '0') {
						var roomList = res.body.data.room_info;
						if (roomList)
							this.roomList = this.roomList.concat(roomList);
						var total = res.body.data.total;
						if (this.roomList.length >= total) {
							this.roomLoadingType = 'noMore';
						} else {
							this.roomLoadingType = 'more';
						}
					} else {
						this.roomLoadingType = 'more';
						console.log(res.body.status.errorDesc);
					}
					if (callback) callback();
				}, true);
			},
			//详情
			navToRoom(item) {
				let id = item.productUuid;
				uni.navigateTo({
					url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + item.roomid
				})
			},
			// 查询所有资源标签
			inquiryResourceTag() {
				let searchData = {
					'tagType': 'RESOURCE'
				};
				this.$api.request.inquiryTag(searchData, res => {
					if (res.body.status.statusCode === '0') {
						this.tagList = res.body.data.tags;
					}
				}, true);
			},
			//查询新人福利
			inquiryProfitWelfare() {
				let that = this;
				this.$api.request.inquiryProfitWelfare({}, res => {
					if (res.body.status.statusCode === '0') {
						this.giftList = res.body.data.welfares;
						var giftResourceList = [];
						var giftCouponList = [];
						this.giftList.forEach(function(gift, index) {
							if (gift.welfareType == 'RESOURCE') {
								giftResourceList.push(gift);
							} else if (gift.welfareType == 'COUPON') {
								giftCouponList.push(gift);
							} else if (gift.welfareType == 'POINT') {
								that.giftPoint = gift;
							}
						})
						this.giftResourceList = giftResourceList;
						this.giftCouponList = giftCouponList;
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//领取新人福利
			receiveProfitWelfare() {
				this.receiveLoading = true;
				this.$api.request.receiveProfitWelfare({
					userUuid: this.userInfo.userUuid
				}, res => {
					this.receiveLoading = false;
					if (res.body.status.statusCode === '0') {
						this.$api.msg('领取成功');
						this.receiveGiftMessage = '';
						this.showGift = false;
						//标记新人福利已领取
						this.userInfo.profitWelfareReceived = true;
					} else {
						this.receiveGiftMessage = res.body.status.errorDesc
					}
				});
			}

		}
	}
</script>

<style lang="scss">
	page {
		background: $bg-color-light;
	}

	.container {
		margin: 0 $page-row-spacing;
	}



	.carousel {
		width: 100%;
		height: 250upx;

		.carousel-item {
			width: 100%;
			height: 100%;
			// padding: 0 28upx;
			overflow: hidden;
		}

		image {
			width: 100%;
			height: 100%;
			border-radius: 10upx;
		}
	}

	// 广告栏区域
	.ad-1 {
		// width: 100%;
		height: 210upx;
		margin: 10upx 0;
		background: #fff;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.swiper-box {
		height: 100vh;
		width: 100%;
	}

	/* 标签区域 */
	.tag-section {
		white-space: nowrap;
		width: 100%;

		.tag-group {
			display: inline-block;
			vertical-align: top;
		}

		.tag-item {
			font-size: $font-sm;
			font-weight: bold;
			color: $font-color-dark;
			width: 160upx;
			padding: 20upx;
			margin: 10upx 10upx 10upx 0;
			text-align: center;
			background: $bg-color-base;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		image {
			width: 88upx;
			height: 88upx;
			margin-bottom: 14upx;
			border-radius: 50%;
			opacity: .7;
			box-shadow: 4upx 4upx 20upx rgba(250, 67, 106, 0.3);
		}
	}

	/* 直播间 */
	.room-list {
		display: flex;
		flex-wrap: wrap;

		.room-item {
			width: 48%;
			margin: 1%;
			background: #fff;
		}

		.image-wrapper {
			width: 100%;
			height: 330upx;
			border-radius: 3px;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}

		.title {
			font-size: $font-base;
			color: $font-color-dark;
			line-height: 80upx;
		}

		.desc-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-right: 10upx;
			font-size: 24upx;
			color: $font-color-light;
		}
	}

	//新人领取积分和优惠券
	.gift {
		margin: 30% 17% 10% 17%;
		padding: 15px;
		background-color: $bg-color-light;
		border-radius: 10px;

		.gift-title {
			color: $font-color-dark;
			font-size: $font-base;
			font-weight: 700;
			text-align: center;
		}

		.gift-desc {
			color: $font-color-base;
			font-size: $font-sm;
			text-align: center;
		}

		.gift-image {
			margin-top: 10px;
			text-align: center;

			image {
				width: 75px;
				height: 75px;
			}
		}

		.gift-content {
			margin-top: 20px;

			.gift-item {
				background-color: $bg-color-base;
				padding: 10px;
				margin-top: 10px;
				height: 35px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.gift-item-label {
					color: $font-color-dark;
					font-weight: bold;
					font-size: $font-sm;
				}

				.gift-item-value {
					text-align: center;

					button {
						background-color: $bg-color-dark;
						color: #fff;
						font-size: $font-base;
						height: 30px;
						line-height: 30px;

						.tip {
							&:after {
								content: '积分';
								font-size: $font-sm;
							}
						}
					}
				}
			}
		}

		.gift-message {
			margin-top: 10px;
			color: $font-color-selected;
			font-size: $font-base;
			text-align: center;
		}

		.gift-action {
			margin-top: 30px;
			text-align: center;

			button {
				background-color: $bg-color-dark;
				color: #fff;
				height: 35px;
				line-height: 35px;
				font-size: $font-base;
				font-weight: 700;
			}
		}
	}

	.gift-close {
		display: flex;
		justify-content: center;
		margin-top: 20px;
		color: #fff;
	}
</style>